/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

    //
//  BALibrarySelectionViewController.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 8/6/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BALibrarySelectionViewController.h"
#import "BARPCManager.h"
#import "BALibrary.h"
#import "BAUtils.h"
#import "BALoginViewController.h"
#import "BALibrarySettings.h"
#import "BASearchableTableViewController.h"
#import "BALibrarySettings.h"
#import "JSONEncodingHelperMethods.h"
#import "BASettingsUserDefaultsKeys.h"
#import "BARootViewController.h"
#import "BADebugServerSelectorViewController.h"


@interface BALibrarySelectionViewController () {
    NSDate* lastDebugTripleClick;
}

//@property (strong, nonatomic) NSArray* libraries;
@property (strong, nonatomic) NSMutableDictionary *nameToCustomerIdMap;
@property (strong, nonatomic) NSDictionary* customerIdToLibraryNameMap;
@property (strong, nonatomic) BASearchableTableViewController *searchableTableView;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;
@property (weak, nonatomic) IBOutlet UIView *searchFieldPlaceHolder;
//@property (weak, nonatomic) IBOutlet UILabel *headerLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchFieldHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchFieldToLabelConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelToTopConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *statusbarTintHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoToTopConstraint;

@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UIImageView *appNameImageView;

@property (weak, nonatomic) IBOutlet UIImageView *backgroundImage;

@end

@implementation BALibrarySelectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.searchableTableView setTextFieldEnabled:YES];
    [self.searchableTableView removeSelection];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7

    if ([[BAUtils instance] iOSMajorVersion] < 7) {
        self.statusbarTintHeightConstraint.constant = 0;
    }
    
    bool isIPad = RD_IS_IPAD;
    
    if (isIPad) {
        [self.backgroundImage setImage:[UIImage imageNamed:@"libsel-bg2-ipad.jpg"]];
        [self.logoImageView setImage:[UIImage imageNamed:@"library-selection-logo-ipad"]];
        [self.appNameImageView setImage:[UIImage imageNamed:@"library-selection-app-name-ipad"]];
        self.logoToTopConstraint.constant = 110;
        self.labelToTopConstraint.constant = 190;
    }
    
    self.searchableTableView = [[BASearchableTableViewController alloc] initWithNibName:@"BASearchableTableViewController" bundle:nil];
    self.searchableTableView.placeHolderText = @"Find dit bibliotek...";
    self.searchableTableView.font = [UIFont fontWithName:@"Roboto-Light" size:isIPad ? 16 : 14];
    self.searchableTableView.highlightFont = [UIFont fontWithName:@"Roboto-Medium" size:isIPad ? 16 : 14];
    [self addChildViewController:self.searchableTableView];
    self.searchableTableView.delegate = self;
    [self.searchFieldPlaceHolder addSubview:self.searchableTableView.view];
    self.searchableTableView.view.frame = self.searchFieldPlaceHolder.bounds;

    // Load the cached list of library names if available.
    //NSArray *librariesJsonObj = [[NSUserDefaults standardUserDefaults] arrayForKey:BASETTINGS_LIBRARIES_KEY];
    NSDictionary *userDefaultsCustomerToNameMap = [[NSUserDefaults standardUserDefaults] dictionaryForKey:BASETTINGS_LIBRARYNAMES_KEY];
    if (userDefaultsCustomerToNameMap) {
        self.customerIdToLibraryNameMap = userDefaultsCustomerToNameMap;
    }
    
    // And fetch a fresh list.
    [self fetchLibraryNames];
    
    // Check whether we already have selected a library.
    if ([[BALibrarySettings instance] libraryObject]) {
        BALibrary *lib = [[BALibrarySettings instance] libraryObject];
        if (lib != nil && [lib.customerId length] > 0) {
            [self fetchLibrarySettingsForLibrary:lib.customerId];
            [self gotoLoginDialogForLibrary:lib];
        }
    }
    
    UITapGestureRecognizer* gest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(debugMultiTapRecognized:)];
    gest.numberOfTapsRequired = 3;
    [self.appNameImageView addGestureRecognizer:gest];
    self.appNameImageView.userInteractionEnabled=YES;
    
    UITapGestureRecognizer* gest2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(someWhereElseClicked:)];
    gest2.cancelsTouchesInView=NO;
    [self.view addGestureRecognizer:gest2];

    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self addKeyboardObserver];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self removeKeyboardObserver];
}

- (void)addKeyboardObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeKeyboardObserver{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)dealloc
{
    [self removeKeyboardObserver];
}

-(void)debugMultiTapRecognized:(id)sender
{
    if (lastDebugTripleClick==nil) {
        lastDebugTripleClick=[NSDate date];
    } else {
        if ([lastDebugTripleClick timeIntervalSinceNow]<-2) {
            lastDebugTripleClick=nil;
        } else {
            BADebugServerSelectorViewController* d = [BADebugServerSelectorViewController new];
            [self.view addSubview:d.view];
            [self addChildViewController:d];
        }
    }
}

-(NSUInteger)supportedInterfaceOrientations{
    if (RD_IS_IPAD) {
        return UIInterfaceOrientationMaskLandscape;
    } else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

/* old code
-(void)fetchLibraryList
{
    
    [BARPCManager getLibrariesAsyncFromView:self
                                resultBlock:^(NSArray *result) {
                                    
                                    self.libraries = result;
                                    [self.loadingIndicator stopAnimating];
                                    
                                    @try {
                                        NSArray *jsonRepr = [JSONEncodingHelperMethods jsonifyArrayOfObjects:result];
                                        if (jsonRepr) {
                                            [[NSUserDefaults standardUserDefaults] setObject:jsonRepr forKey:BASETTINGS_LIBRARIES_KEY];
                                            [[NSUserDefaults standardUserDefaults] synchronize];
                                        }
                                        else {
                                            DLog(@"Error generating JSON representation of library list.");
                                        }
                                        
                                        // Update the current library object (if any exists)
                                        if ([[BALibrarySettings instance] libraryObject]) {
                                            BALibrary *lib = [[BALibrarySettings instance] libraryObject];
                                            for (BALibrary *libInList in result) {
                                                if ([lib.customerId isEqualToString:libInList.customerId]) {
                                                    [[BALibrarySettings instance] setLibraryObject:libInList];
                                                }
                                            }
                                        }
                                        
                                    }
                                    @catch (NSException *exception) {
                                        NSLog(@"Error persisting library object: %@",exception);
                                    }
                                }
                                 errorBlock:^(int code, NSString *error) {
                                     [self.loadingIndicator stopAnimating];
                                     DLog(@"Error fetching list of libraries. Code=%d, message=\"%@\"", code, error);
                                     if (self.libraries == nil) {
                                         UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Netværksproblemer" message:@"Kunne ikke hente listen af biblioteker" delegate:self cancelButtonTitle:@"Prøv igen" otherButtonTitles:nil];
                                         [v show];
                                     }
                                 }
     ];

}
 */


-(void)fetchLibraryNames
{
    [BARPCManager getLibraryNamesFromView:self
                              resultBlock:^(NSDictionary *libraryNames) {
                                  [self.loadingIndicator stopAnimating];

                                  if (libraryNames!=nil && [libraryNames count]>0) {
                                      self.customerIdToLibraryNameMap = libraryNames;
                                      @try {
                                              [[NSUserDefaults standardUserDefaults] setObject:libraryNames forKey:BASETTINGS_LIBRARYNAMES_KEY];
                                              [[NSUserDefaults standardUserDefaults] synchronize];
                                      }
                                      @catch (NSException *exception) {
                                          NSLog(@"Error persisting library names object: %@",exception);
                                      }
                                  }
                              } errorBlock:^(int errorCode, NSString *errorMessage) {
                                  [self.loadingIndicator stopAnimating];
                                  DLog(@"Error fetching list of libraries. Code=%d, message=\"%@\"", errorCode, errorMessage);
                                  if (self.customerIdToLibraryNameMap == nil) {
                                      UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Netværksproblemer"
                                                                                  message:[NSString stringWithFormat:@"Kunne ikke hente listen af biblioteker. %@",errorMessage]
                                                                                 delegate:self
                                                                        cancelButtonTitle:@"Prøv igen"
                                                                        otherButtonTitles:nil];
                                      [v show];
                                  }
 
                              }];
}

-(void)fetchLibrarySettingsForLibrary:(NSString*)customerId
{
    [[BARPCManager instance] setAndConfigureLibraryId:customerId];
    [BARPCManager getLibrarySettingsFromView:self
                                 resultBlock:^(BALibrary *libraryObject) {
                                     if (libraryObject!=nil) {
                                         [[BALibrarySettings instance] setLibraryObject:libraryObject];
                                     }
                                 }
                                  errorBlock:^(int errorCode, NSString *errorMessage) {
                                      
                                  }];
}


-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [self fetchLibraryNames];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)someWhereElseClicked:(id)sender
{
    [self.searchableTableView resignFirstResponder];
}


/* old code
- (void)setLibraries:(NSArray *)libraries
{
    _libraries = libraries;
    self.nameToLibraryMapping = [NSMutableDictionary new];
    for (BALibrary *library in libraries) {
        NSString *name = library.name;
        if (name == nil || [name length] == 0) {
            name = library.customerId; //Hack to show lib id if no name set
        }
        [self.nameToLibraryMapping setObject:library forKey:name];
    }
    self.searchableTableView.contents = [self.nameToLibraryMapping allKeys];
}
*/

-(void)setCustomerIdToLibraryNameMap:(NSDictionary *)customerIdToLibraryNameMap
{
    _customerIdToLibraryNameMap = customerIdToLibraryNameMap;
    self.nameToCustomerIdMap = [NSMutableDictionary new];
    for (NSString* custId in [customerIdToLibraryNameMap allKeys]) {
        NSString *name = [customerIdToLibraryNameMap objectForKey:custId];
        if (name == nil || [name length] == 0) {
            name = custId; //Hack to show lib id if no name set
        }
        [self.nameToCustomerIdMap setObject:custId forKey:name];
    }
    self.searchableTableView.contents = [self.nameToCustomerIdMap allKeys];
}

#pragma mark - Keyboard handling

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    DLog(@"keyboard userinfo: %@",info);
    NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    if (kbFrame==nil) {
        return; //bail out
    }
    NSTimeInterval animationDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [kbFrame CGRectValue];

    CGFloat height;
    CGFloat screenHeight;
    if ([[BAUtils instance] iOSMajorVersion] >= 8)
    {
        height = keyboardFrame.size.height;
        screenHeight = [UIScreen mainScreen].bounds.size.height;
        
    } else {
        BOOL isPortrait = UIInterfaceOrientationIsPortrait(self.interfaceOrientation);
        height = isPortrait ? keyboardFrame.size.height : keyboardFrame.size.width;
        screenHeight = isPortrait ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width;
    }

    CGFloat searchFieldHeight  = screenHeight - self.searchFieldPlaceHolder.frame.origin.y - height - 10 - ([[BAUtils instance] iOSMajorVersion] < 7 ? 20 : 0);
    if (searchFieldHeight < 46) {
        searchFieldHeight = 46;
    }
    
    [UIView animateWithDuration:animationDuration
                     animations:^{
                         [self.view layoutIfNeeded];
                     }
                     completion:^(BOOL finished) {
                         self.searchFieldHeightConstraint.constant = searchFieldHeight;
                         [UIView animateWithDuration:animationDuration
                                               delay:0
                                             options:UIViewAnimationOptionBeginFromCurrentState
                                          animations:^{
                                              [self.view layoutIfNeeded];
                                          } completion:nil];
                     }];
}

/* not used
-(void)keyboardWillHide:(NSNotification *)notification {
}
 */

#pragma mark - BASearchableTableViewControllerDelegate

- (void)searchableTableView:(id)tableView didSelectItem:(NSString *)item
{
    if ([item length]>0) {
        NSString* newCustomerId = [self.nameToCustomerIdMap objectForKey:item];
        if (newCustomerId!=nil && [newCustomerId length]>0) {
            [self.searchableTableView resignFirstResponder];
            [self.searchableTableView setTextFieldEnabled:NO];
            
            BALibrary* currentLib = [BALibrarySettings instance].libraryObject;
            if (currentLib!=nil && [currentLib.customerId isEqualToString:newCustomerId]) {
                [self fetchLibrarySettingsForLibrary:newCustomerId]; //we already have the customer settings from cache, but we refresh them anyway
                [self gotoLoginDialogForLibrary:currentLib];
            } else {
                [self.loadingIndicator startAnimating];
                [[BARPCManager instance] setAndConfigureLibraryId:newCustomerId];
                self.searchFieldHeightConstraint.constant = 46;
                [UIView animateWithDuration:0.5
                                 animations:^{
                                     [self.view layoutIfNeeded];
                                 }];
                [BARPCManager getLibrarySettingsFromView:self
                                             resultBlock:^(BALibrary *newLibrary) {
                                                 [self.loadingIndicator stopAnimating];
                                                 [self gotoLoginDialogForLibrary:newLibrary];
                                                 
                                             }
                                              errorBlock:^(int errorCode, NSString *errorMessage) {
                                                  [self.loadingIndicator stopAnimating];
                                                  [self.searchableTableView setTextFieldEnabled:YES];
                                                  UIAlertView* v = [[UIAlertView alloc] initWithTitle:@"Netværksproblemer"
                                                                                              message:[NSString stringWithFormat:@"Kunne ikke hente bibliotekets data. %@",errorMessage]
                                                                                             delegate:self
                                                                                    cancelButtonTitle:@"OK"
                                                                                    otherButtonTitles:nil];
                                                  [v show];
                                              }];
                
            }
        }
    }
    
}

-(void)searchableTableViewDidBeginEditing:(id)tableView
{
    //BOOL isPortrait = UIInterfaceOrientationIsPortrait(self.interfaceOrientation);
    //CGFloat screenHeight = isPortrait ? [UIScreen mainScreen].bounds.size.height : [UIScreen mainScreen].bounds.size.width;

    bool isIPad = RD_IS_IPAD;
    
    self.searchFieldToLabelConstraint.constant = isIPad ? 15 : 10;
    self.labelToTopConstraint.constant = isIPad ? 50 : 40;
    self.searchFieldHeightConstraint.constant = 180;

    [UIView animateWithDuration:0.25
                     animations:^{
                         self.logoImageView.alpha = 0;
                         [self.view layoutIfNeeded];
                     }];

}

#pragma mark -

- (void)gotoLoginDialogForLibrary:(BALibrary*)lib
{
    [[BARPCManager instance] setAndConfigureLibraryId:lib.customerId];
    BALibrarySettings* libsettings = [BALibrarySettings instance];
    [libsettings setLibraryObject:lib];
    [libsettings libraryObjectChanged];
    if ([libsettings isImfEnabled] == NO && [libsettings isLibrarianModeAllowed] == NO) {
        // Bypass the login screen altogether.
        [[BARootViewController instance] switchToMainTabBarAppMode];
    }
    else {
        BALoginViewController* lvc = [BALoginViewController new];
        [self.navigationController pushViewController:lvc animated:YES];
    }
}


@end
